package com.xzit.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class DownLoadServlet extends HttpServlet {
    private String dir ; // 下载文件所在父目录
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("fileId");// 获取下载链接的文件id参数
        dir = getServletContext().getRealPath("/WEB-INF/downloads/");

        // 建立下载的目标文件
        File target = new File(dir+id);
        InputStream input = null;
        ServletOutputStream output = null;
        if(target.exists()){
            input = new FileInputStream(target);
            // 设置文件临时存储的缓冲区
            byte [] datas  = new byte[10240];
            int count =0; // 读取字节的计数器
            // 设置响应头内容，告知浏览器本次响应是文件下载
            response.setHeader("content-disposition",
                    "attachment;filename="+URLEncoder.encode(target.getName(),"UTF-8"));
            output = response.getOutputStream();// 获取响应给客户端的文件输出流
            /* 读取文件到缓冲区，响应发送输出流到客户端浏览器*/
            while((count = input.read(datas, 0, datas.length)) > 0){
                output.write(datas, 0, count); // 输入到客户端
            }
            output.flush();
            output.close();
            input.close();
        }else{// 如果不存在
            response.sendRedirect("../tip.jsp");// 定位到提示页面
        }

    }
}
